<script setup>
import { h,computed,ref,onMounted } from "vue";
// import { Plus, CirclePlusFilled, CirclePlus, Check, CircleCheck } from '@element-plus/icons-vue';

import { RouterLink,RouterView } from "vue-router";
import { NIcon, NConfigProvider } from "naive-ui";

import {
  Code as CodeIcon, Home as HomeIcon,
  LogoMarkdown as MditorIcon,
  FileTrayFull as RichTextIcon,
  SettingsSharp as SettingIcon,
  Checkbox as TodoIcon,
  Navigate as NavigateIcon,
  DocumentText as DocIcon,
  AlertCircleSharp as AboutIcon,
  Barcode as OcrIcon,
  Bug as FeedbackIcon,
  Book as InstructionsIcon,
  Copy as DiffIcon,
  ExtensionPuzzle as SegmentIcon
} from '@vicons/ionicons5'

import { darkTheme, lightTheme } from 'naive-ui'
import mitt from './utils/event.js'
import {GetConnectList,ConnectSDB} from "../wailsjs/go/main/App.js";
import { ElMessage } from "element-plus"
const renderIcon = (icon) => {
  return () => h(NIcon, null, { default: () => h(icon) });
}


// 假设这是你的下拉选项数据源
let dropdownOptions = ref([]);

let dynamicDatabaseText = ref("连接数据库")


// 初始化下拉选项数据
const fetchDropdownOptions = async () => {
  // const response = [
  //   { id: 1, actionName: 'Action 1'},
  //   { id: 2, actionName: 'Action 2'},
  //   // 更多数据...
  // ];
  const response = await GetConnectList()
  if (response.data.length === 0){
    ElMessage.warning('无数据库配置项，请到【数据库设置】菜单中添加数据库后再试！')
  }
  dropdownOptions.value = response.data.map(item => ({
    text: item.name,
    id: item.id,
  }));

  // 这里模拟异步获取数据，实际项目中可能是从API获取
  // dropdownOptions.value = [
  //   { text: 'Action 1', icon: Plus },
  //   { text: 'Action 2', icon: CirclePlusFilled },
  //   // ...更多选项
  // ];
};

// 下拉菜单可见性变化时触发
const handleDropdownVisibleChange = (visible) => {
  if (visible) {
    // 当下拉菜单变为可见时，刷新选项
    fetchDropdownOptions();
  }
};

// 选项点击事件处理
const handleOptionClick = (item) => {
  console.log(item)
  console.log(`Clicked on ${item.text}`);
  // 在这里处理选项被点击的逻辑
  ConnectSDB(item.id).then(res =>{
    if (res.code === 200){
      ElMessage.success(res.msg)
      dynamicDatabaseText.value = `${item.text}`;
    }else {
      ElMessage.error(res.msg)
      dynamicDatabaseText.value = `连接失败`;
    }
    console.log(res)
  })
};

// 页面挂载完成后初始化数据
onMounted(() => {
  fetchDropdownOptions();
});

const collapsed = ref(false);
const menuOptions = [
  // 示例菜单数据结构，需根据实际路由结构调整
  {
    icon: HomeIcon,
    label: '主页',
    path: '/',
  },
  {
    icon: SettingIcon,
    label: '数据库设置',
    path: '/dbSetting',
  },
  {
    icon: AboutIcon,
    label: '关于',
    path: '/about',
  },
  // 更多菜单项...
];

const getIconComponent = (iconName) => {
  return iconName;
};


const changeTheme = () => {
  if (this.switchTheme) {
    this.myTheme = darkTheme
    localStorage.setItem("theme", 1)
    mitt.emit("theme", "1")
    // this.app.UpdateConfigItem({ name: "theme", value: "dark", type: "sysconf" }).then((res) => {
    //   if(res.code !== 200) {
    //
    //   }
    // })
  } else {
    this.myTheme = lightTheme
    localStorage.setItem("theme", 0)
    mitt.emit("theme", "0")
    // this.app.UpdateConfigItem({ name: "theme", value: "light", type: "sysconf" }).then((res) => {
    //   if(res.code !== 200) {
    //
    //   }
    // })
  }
}

const getInitData = () => {
  var theme = localStorage.getItem("theme")
  if (theme !== "" && theme !== null){
    if (theme === "0"){
      this.myTheme = lightTheme
      mitt.emit("theme", "0")
    }else {
      this.myTheme = darkTheme
      mitt.emit("theme", "1")
    }
  }else {
    localStorage.setItem('theme', 0)
    this.myTheme = lightTheme
    mitt.emit("theme", "0")
  }
  // this.app.GetConfigMap().then((res) => {
  //   if (res.sysconf.theme == 'light') {
  //     // 初始化项目时将主题保存在localStorage中
  //     localStorage.setItem('theme', 1)
  //     this.myTheme = lightTheme
  //   } else {
  //     localStorage.setItem('theme', 0)
  //     this.myTheme = darkTheme
  //   }
  // })
}

// export default {
//   components: {
//     NConfigProvider
//   },
//   setup() {
//
//   },
//   data() {
//   },
//   mounted() {
//     this.getInitData()
//   },
//   methods: {
//     changeTheme() {
//       if (this.switchTheme) {
//         this.myTheme = darkTheme
//         localStorage.setItem("theme", 1)
//         mitt.emit("theme", "1")
//         // this.app.UpdateConfigItem({ name: "theme", value: "dark", type: "sysconf" }).then((res) => {
//         //   if(res.code !== 200) {
//         //
//         //   }
//         // })
//       } else {
//         this.myTheme = lightTheme
//         localStorage.setItem("theme", 0)
//         mitt.emit("theme", "0")
//         // this.app.UpdateConfigItem({ name: "theme", value: "light", type: "sysconf" }).then((res) => {
//         //   if(res.code !== 200) {
//         //
//         //   }
//         // })
//       }
//     },
//     getInitData() {
//       var theme = localStorage.getItem("theme")
//       if (theme !== "" && theme !== null){
//         if (theme === "0"){
//           this.myTheme = lightTheme
//           mitt.emit("theme", "0")
//         }else {
//           this.myTheme = darkTheme
//           mitt.emit("theme", "1")
//         }
//       }else {
//         localStorage.setItem('theme', 0)
//         this.myTheme = lightTheme
//         mitt.emit("theme", "0")
//       }
//       // this.app.GetConfigMap().then((res) => {
//       //   if (res.sysconf.theme == 'light') {
//       //     // 初始化项目时将主题保存在localStorage中
//       //     localStorage.setItem('theme', 1)
//       //     this.myTheme = lightTheme
//       //   } else {
//       //     localStorage.setItem('theme', 0)
//       //     this.myTheme = darkTheme
//       //   }
//       // })
//     }
//   }
// }

</script>

<template>
  <div class="common-layout">
    <el-container style="height: 100vh">
      <el-aside  bordered collapse-mode="width" :collapsed-width="65" :width="200" :collapsed="collapsed"
                  show-trigger @collapse="collapsed = true" @expand="collapsed = false"
                  style="--wails-draggable:drag; opacity: 1;">
        <el-menu
            router
            :default-active="$route.path"
            :collapse="collapsed"
            :collapse-transition="false"
            :unique-opened="true"  style="margin-top: 40px;"
        >
          <!-- 对顶级菜单进行循环 -->
          <template v-for="(item, index) in menuOptions" :key="item.key">
            <!-- 如果有子菜单，则渲染为el-sub-menu -->
            <el-sub-menu v-if="item.children && item.children.length > 0" :index="String(index)">
              <template #title>
                <el-icon><component :is="getIconComponent(item.icon)"/></el-icon>
                {{ item.label }}
              </template>
              <el-menu-item v-for="child in item.children" :key="child.key" :index="child.path">
                {{ child.label }}
              </el-menu-item>
            </el-sub-menu>
            <!-- 如果没有子菜单，则直接渲染为el-menu-item -->
            <el-menu-item v-else :key="item.key" :index="item.path">
              <el-icon><component :is="getIconComponent(item.icon)"/></el-icon>
              {{ item.label }}
            </el-menu-item>
          </template>
        </el-menu>

<!--        <el-dropdown v-if="!collapsed" class="bottom-right-dropdown" trigger="click">-->

<!--          <span class="el-dropdown-link" style="font-size: 14px; display: inline-flex; align-items: center;">-->
<!--            <el-icon :size="20" style="vertical-align: middle; margin-right: 4px;"><Operation /></el-icon>-->
<!--            切换数据库<el-icon class="el-icon&#45;&#45;right"><arrow-down /></el-icon>-->
<!--          </span>-->
<!--          <template #dropdown>-->
<!--            <el-dropdown-menu>-->
<!--              <el-dropdown-item :icon="Plus">Action 1</el-dropdown-item>-->
<!--              <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>-->
<!--              <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>-->
<!--              <el-dropdown-item :icon="Check">Action 4</el-dropdown-item>-->
<!--              <el-dropdown-item :icon="CircleCheck">Action 5</el-dropdown-item>-->
<!--            </el-dropdown-menu>-->
<!--          </template>-->
<!--        </el-dropdown>-->
        <el-dropdown
            v-if="!collapsed"
            class="bottom-right-dropdown"
            trigger="click"
            @visible-change="handleDropdownVisibleChange"
        >

          <span class="el-dropdown-link" style="font-size: 14px; display: inline-flex; align-items: center;">
            <el-icon :size="20" style="vertical-align: middle; margin-right: 4px;"><Operation /></el-icon>
            {{ dynamicDatabaseText }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                  v-for="(item, index) in dropdownOptions"
                  :key="index"
                  :icon="item.icon"
                  @click.native="handleOptionClick(item)"
              >{{ item.text }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-aside>
      <el-container style="background-color: rgb(245, 245, 245) ;width: 100%">
<!--        <el-header style="background-color: rgb(245, 245, 245)">-->
<!--          <div>-->
<!--            <img src="../assets/logo2.png" alt="" height="50px"/>-->
<!--            <span>后台管理系统</span>-->
<!--          </div>-->

<!--        </el-header>-->
        <el-main>
          <router-view />
        </el-main>
<!--        <el-footer>Footer</el-footer>-->
      </el-container>
    </el-container>
  </div>
</template>
<style scoped>.bottom-right-dropdown {
  position: absolute;
  bottom: 20px; /* 调整距离底部的距离 */
  left: 16px; /* 调整距离右侧的距离 */
}
</style>

<style>

.justify-content-center {
  justify-content: center;
  text-align: center; /* 如果内部有文本，这句可帮助文本居中 */
  width: 100%; /* 确保容器宽度适应父元素 */
}

.el-aside{
  background-color: rgb(255, 255, 255);
  height: 100%;
}
.el-header{
  background-color: #373d41;
  display: flex;
  justify-content: space-between;
  padding-left: 0;
  align-items: center;
  color: #000000;
  font-size: 20px;

}

.switchBtnPar {
  position: relative;
}

.switchBtn {
  position: absolute;
  left: 50%;
  transform: translate(-50%);
}



body {
  margin: 0;
}
</style>
